import { useAPIUtils } from "@/components/APIUtilsProvider";
import PageLayout from "@/components/PageLayout";
import UserPill from "@/components/UserPill";
import { useDeliveryVendorQuery } from "@/hooks/useDeliveryVendorQuery";
import { Box, Button, Flex, Grid, Text, Timeline, Title } from "@mantine/core";
import dayjs from "dayjs";
import { useParams } from "react-router-dom";
import StatusBadge from "./StatusBadge";

export default function OrderDetails() {
  return (
    <PageLayout title={"订单详情"}>
      <Grid w="96%">
        <Grid.Col span={7}>
          <Basics />
        </Grid.Col>
        <Grid.Col span={4} offset={1}>
          <OrderTimeline />
        </Grid.Col>
      </Grid>
    </PageLayout>
  );
}

function OrderTimeline() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const timelineQuery = tanstackQuery(`/api/admin/orders/${id}/timeline`);

  if (!timelineQuery.data || timelineQuery.data.length === 0) return <></>;

  return (
    <>
      <Title order={6} mb={"lg"}>
        订单历史
      </Title>
      <Timeline
        active={timelineQuery.data.length - 1}
        lineWidth={2}
        bulletSize={18}
      >
        {timelineQuery.data.map((v, i) => (
          <Timeline.Item key={i} title={v.title} bulletSize={12}>
            <Text c="dimmed" size="sm">
              {v.message}
            </Text>
            <Text size="xs" mt={4}>
              {dayjs(v.createdAt).format("YYYY/MM/DD HH:mm:ss")}
            </Text>
          </Timeline.Item>
        ))}
      </Timeline>
    </>
  );
}

const Descriptions = ({ title, data, tools }) => {
  return (
    <Box padding="md">
      {title && (
        <Flex justify={"space-between"} align={"baseline"}>
          <Title order={6} mb={"lg"}>
            {title}
          </Title>
          {tools}
        </Flex>
      )}

      <Grid gutter="0" style={{ border: "0.1px solid rgba(0, 0, 0, 0.1)" }}>
        {data.map((item, index) => (
          <>
            <Grid.Col
              span={2}
              bg={"gray.1"}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text weight={100} size="sm">
                {item.label}
              </Text>
            </Grid.Col>
            <Grid.Col
              span={item.block ? 10 : 4}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text>{item.value}</Text>
            </Grid.Col>
          </>
        ))}
      </Grid>
    </Box>
  );
};

function Basics() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const orderQuery = tanstackQuery(`/api/orders/${id}`);

  const { format } = useDeliveryVendorQuery(orderQuery.data?.deliveryVendorId);

  if (!orderQuery.data) {
    return <></>;
  }

  const order = orderQuery.data;

  const tools = (
    <Button.Group>
      <Button
        variant="default"
        disabled={!order.deliveryNo}
        onClick={() => window.open(`${format}${order.deliveryNo}`, "_blank")}
      >
        查看物流
      </Button>
    </Button.Group>
  );

  const descriptionsData = [
    { label: "商品", value: order.productName },
    { label: "数量", value: order.quantity },
    {
      label: "状态",
      value: <StatusBadge status={order.status} />,
      block: true,
    },
    { label: "单价", value: order.unitPrice },
    { label: "总价", value: order.totalPrice },
    { label: "单品积分", value: order.unitPv },
    { label: "总积分", value: order.totalPv },
    { label: "买家", value: <UserPill user={order.buyer} />, block: true },
    { label: "经营店铺", value: <UserPill user={order.firstSeller} /> },
    { label: "经营利润", value: order.firstSellerProfit },
    { label: "管理店铺", value: <UserPill user={order.secondSeller} /> },
    { label: "育成利润", value: order.secondSellerProfit },
    { label: "总部应收款", value: order.headQuarterPrice, block: true },
    { label: "买家备注", value: order.remark, block: true },
    {
      label: "创建时间",
      value: dayjs(order.createdAt).format("YYYY/MM/DD HH:mm:ss"),
      block: true,
    },
  ];
  return (
    <Descriptions
      title={`订单流水号: ${id}`}
      data={descriptionsData}
      tools={tools}
    />
  );
}
